//
//  KDBaseNewsController.m
//  WangJingApp
//
//  Created by 魏强 on 17/1/4.
//  Copyright © 2017年 KDTech. All rights reserved.
//

#import "KDBaseNewsController.h"
#import "KDBaseChildNewsController.h"
CGFloat const BTN_WIDTH = 78;
@interface KDBaseNewsController ()<UIScrollViewDelegate>
@property (nonatomic, strong) NSMutableArray *titleButtons;
@property (nonatomic, weak) UIButton *selectButton;
@property (nonatomic, weak) UIScrollView *titleScrollView;
@property (nonatomic, weak) UIScrollView *contentScrollView;

@property (nonatomic, assign) BOOL isInitialize;
/**  是否需要按钮居中 */
@property (nonatomic, assign) BOOL needDisplayCenter;
/**  底部绿线 */
@property (nonatomic, weak) UIView *underLine;
/**  0：正常的；1:管理的 */
@property (nonatomic, assign) NSInteger btnType;
/**  <#Description#> */
@property (nonatomic, strong) KDBaseChildNewsController *selectCtrl;

@end

@implementation KDBaseNewsController

- (NSMutableArray *)titleButtons
{
    if (_titleButtons == nil) {
        _titleButtons = [NSMutableArray array];
    }
    return _titleButtons;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (_isInitialize == NO) {
        
        
        _isInitialize = YES;
    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
//    self.navigationItem.title = @"网易新闻";
    
    // 1.添加标题滚动视图
    [self setupTitleScrollView];
    
    // 2.添加内容滚动视图
    [self setupContentScrollView];
    
    
    // iOS7以后,导航控制器中scollView顶部会添加64的额外滚动区域
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 5.处理标题点击
    
    // 6.处理内容滚动视图滚动
    
    // 7.选中标题居中 => 选中标题
    
}

#pragma mark - UIScrollViewDelegate

// 滚动完成的时候调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 获取当前角标
    NSInteger i = scrollView.contentOffset.x / screenW;
    
    // 获取标题按钮
    UIButton *titleButton = self.titleButtons[i];
    
    // 1.选中标题

    [self selButton:titleButton];
    
    // 2.把对应子控制器的view添加上去
    [self setupOneViewController:i];
}

// 只要一滚动就需要字体渐变
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!self.btnType) {
        // 字体缩放 1.缩放比例 2.缩放哪两个按钮
        NSInteger leftI = scrollView.contentOffset.x / screenW;
        NSInteger rightI = leftI + 1;
        _currentIndex = leftI;
        //    KDLog(@"%ld",(long)leftI);
        // 获取左边的按钮
        UIButton *leftBtn = self.titleButtons[leftI];
        NSInteger count = self.titleButtons.count;
        
        // 获取右边的按钮
        UIButton *rightBtn;
        if (rightI < count) {
            rightBtn = self.titleButtons[rightI];
        }
        
        // 0 ~ 1 =>  1 ~ 1.3
        // 计算缩放比例
        CGFloat scaleR = scrollView.contentOffset.x / screenW;
        
        scaleR -= leftI;
        
        // 左边缩放比例
        CGFloat scaleL = 1 - scaleR;
        
        // 缩放按钮  66 193 48
        leftBtn.transform = CGAffineTransformMakeScale(scaleL * 0.3 + 1, scaleL * 0.3 + 1);
        rightBtn.transform = CGAffineTransformMakeScale(scaleR * 0.3 + 1, scaleR * 0.3 + 1);
//        KDLog(@"%@")
        // 颜色渐变
        UIColor *rightColor = [UIColor colorWithRed:scaleR *(66/255.0) green:scaleR *(193/255.0) blue:scaleR *(48/255.0) alpha:1];
        UIColor *leftColor = [UIColor colorWithRed:scaleL *(66/255.0) green:scaleL *(193/255.0) blue:scaleL *(48/255.0)  alpha:1];
        [rightBtn setTitleColor:rightColor forState:UIControlStateNormal];
        [leftBtn setTitleColor:leftColor forState:UIControlStateNormal];
//        if (scaleR ) {
//            <#statements#>
//        }
//        self.underLine.centerX = self.underLine.centerX + rightBtn.width*scaleL;
    }
    
}

/*
 颜色:3种颜色通道组成 R:红 G:绿 B:蓝
 
 白色: 1 1 1
 黑色: 0 0 0
 红色: 1 0 0
 */

#pragma mark - 选中标题
- (void)selButton:(UIButton *)button
{
    if (self.btnType) {
        _selectButton.selected = NO;
        _selectButton.layer.borderColor = WQColor(234, 234, 234).CGColor;
        button.layer.borderColor = KDSelectColor.CGColor;
        button.selected = YES;
        _selectButton = button;
        
    }else{
        _selectButton.transform = CGAffineTransformIdentity;
        [_selectButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setTitleColor:KDSelectColor forState:UIControlStateNormal];
        
        // 标题居中
        if (self.needDisplayCenter) {
            [self setupTitleCenter:button];
        }
        
        // 字体缩放:形变
        button.transform = CGAffineTransformMakeScale(1.3, 1.3);
        
        _selectButton = button;
    }
    if (self.needUnderLine) {
        [UIView animateWithDuration:0.2 animations:^{
            self.underLine.centerX = button.centerX;
//            self.underLine.width = button.width;

        }];
    }
    
}
#pragma mark - 标题居中
- (void)setupTitleCenter:(UIButton *)button
{
    // 本质:修改titleScrollView偏移量
    CGFloat offsetX = button.center.x - screenW * 0.5;
    // 处理最小偏移量
    if (offsetX < 0) {
        offsetX = 0;
    }
    
    // 处理最大偏移量
    CGFloat maxOffsetX = self.titleScrollView.contentSize.width - screenW;
    if (offsetX > maxOffsetX) {
        offsetX = maxOffsetX;
    }
//    NSLog(@"offsetX=%f, maxOffsetX=%f", offsetX,maxOffsetX);
    [self.titleScrollView setContentOffset: CGPointMake(offsetX, 0) animated:YES];
}

#pragma mark - 添加一个子控制器的View
- (void)setSelectCtrl:(KDBaseChildNewsController *)selectCtrl{
    _selectCtrl.selected = NO;
    _selectCtrl = selectCtrl;
    _selectCtrl.selected = YES;
}
- (void)setupOneViewController:(NSInteger)i
{
    
    KDBaseChildNewsController *vc = self.childViewControllers[i];
    if (vc.view.superview) {
        if ([vc isKindOfClass:[KDBaseChildNewsController class]]) {
            self.selectCtrl = vc;

        }
        return;
    }
    CGFloat x = i * [UIScreen mainScreen].bounds.size.width;
    vc.view.frame = CGRectMake(x, 0, screenW  , self.contentScrollView.bounds.size.height);
//    KDLog(@"%@", NSStringFromCGRect(vc.view.frame));
    [self.contentScrollView addSubview:vc.view];
    if ([vc isKindOfClass:[KDBaseChildNewsController class]]) {
        self.selectCtrl = vc;
    }
}

#pragma mark - 处理标题点击
- (void)switchToPage:(NSInteger)page{
    UIButton *btn = self.titleButtons[page];
    [self titleClick:btn];
}
- (void)titleClick:(UIButton *)button
{
    NSInteger i = button.tag;
    
    // 1.标题颜色 变成 红色
    [self selButton:button];
    
    // 2.把对应子控制器的view添加上去
    [self setupOneViewController:i];
    
    // 3.内容滚动视图滚动到对应的位置
    CGFloat x = i * [UIScreen mainScreen].bounds.size.width;
    self.contentScrollView.contentOffset = CGPointMake(x, 0);
}

#pragma mark - 设置所有标题
- (void)setupAllTitle
{
    
    // 已经把内容展示上去 -> 展示的效果是否是我们想要的(调整细节)
    if (self.titleButtons.count) {
        [self.titleButtons removeAllObjects];
        [self.underLine removeFromSuperview];
        for (UIButton *btn in self.titleScrollView.subviews) {
            if ([btn isKindOfClass:[UIButton class]]) {
                [btn removeFromSuperview];
            }
        }
    }
    // 已经把内容展示上去 -> 展示的效果是否是我们想要的(调整细节)
    
    // 1.标题颜色 为黑色
    // 2.需要让titleScrollView可以滚动
    
    // 添加所有标题按钮
    NSInteger count = self.childViewControllers.count;
    CGFloat btnW = BTN_WIDTH;
    CGFloat btnH = self.titleScrollView.bounds.size.height;
    CGFloat btnX = 0;
    CGFloat lastW = 0.0;
    if (self.needUnderLine) {
        //创建底部线
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, btnH - 2, btnW, 2)];
        line.backgroundColor = KDSelectColor;
        self.underLine = line;
        [self.titleScrollView addSubview:line];
    }
    for (NSInteger i = 0; i < count; i++) {
        
        UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
        titleButton.tag = i;
        if (i == 0) {
            btnX = 20;
        }else{
            btnX = lastW;
        }

        UIViewController *vc = self.childViewControllers[i];
        CGRect labelRect = [vc.title boundingRectWithSize:CGSizeMake(screenW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
        [titleButton setTitle:vc.title forState:UIControlStateNormal];
        [titleButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
        if (labelRect.size.width > BTN_WIDTH -10) {//如果宽度大于100，就用大的，小于100，就用默认
            btnW = labelRect.size.width + 30;
        }else{
            btnW = BTN_WIDTH;
        }
        titleButton.frame = CGRectMake(btnX, 0, btnW, btnH);
        titleButton.titleLabel.layer.cornerRadius = 5;
        titleButton.titleLabel.clipsToBounds = YES;
        [titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        titleButton.backgroundColor = RandomColor;
        // 监听按钮点击
        [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
        
        // 把标题按钮保存到对应的数组
        [self.titleButtons addObject:titleButton];
        
        if (i == 0) {
            [self titleClick:titleButton];
            [self.titleScrollView setContentOffset: CGPointMake(0, 0) animated:NO];
        }
        lastW = CGRectGetMaxX(titleButton.frame);
        
        [self.titleScrollView addSubview:titleButton];
    }
    //如果总btn宽度小于titleScrollView.width，就不启动居中展示效果
    self.needDisplayCenter = (lastW > self.titleScrollView.width);
    
    // 设置标题的滚动范围
    self.titleScrollView.contentSize = CGSizeMake(lastW, 0);
    self.titleScrollView.showsHorizontalScrollIndicator = NO;
    
    // 设置内容的滚动范围
    self.contentScrollView.contentSize = CGSizeMake(count * screenW, 0);
    
    // bug:代码跟我的一模一样,但是标题就是显示不出来
    // 内容往下移动,莫名其妙
}
/**
 *  创建有右边按钮的
 */
- (void)setupAllTitleWithRightBtn:(UIButton *)rightBtn
{
    //先去掉之前有的
    if (self.titleButtons.count) {
        [self.titleButtons removeAllObjects];
        for (UIButton *btn in self.titleScrollView.subviews) {
            if ([btn isKindOfClass:[UIButton class]]) {
                [btn removeFromSuperview];
            }
        }
    }
    
    
    // 已经把内容展示上去 -> 展示的效果是否是我们想要的(调整细节)
    // 1.标题颜色 为黑色
    // 2.需要让titleScrollView可以滚动
    
    // 添加所有标题按钮
    NSInteger count = self.childViewControllers.count;
    CGFloat btnW = BTN_WIDTH;
    CGFloat btnH = self.titleScrollView.bounds.size.height;
    CGFloat btnX = 0;
    CGFloat lastW = 0.0;
    for (NSInteger i = 0; i < count; i++) {
        
        UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
        titleButton.tag = i;
        if (i == 0) {
            btnX = 20;
        }else{
            btnX = lastW;
        }
        
        UIViewController *vc = self.childViewControllers[i];
        CGRect labelRect = [vc.title boundingRectWithSize:CGSizeMake(screenW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
        [titleButton setTitle:vc.title forState:UIControlStateNormal];
        [titleButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
        if (labelRect.size.width > BTN_WIDTH -10) {//如果宽度大于100，就用大的，小于100，就用默认
            btnW = labelRect.size.width + 30;
        }else{
            btnW = BTN_WIDTH;
        }
        titleButton.frame = CGRectMake(btnX, 0, btnW, btnH);
//        UIImage *image2 = [UIImage imageNamed:@"btn_background"];
//        CGFloat top = 0; // 顶端盖高度
//        CGFloat bottom = 0 ; // 底端盖高度
//        CGFloat left = 15; // 左端盖宽度
//        CGFloat right = 15; // 右端盖宽度
//        UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
//        image2 = [image2 resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
//        [titleButton setBackgroundImage:image2 forState:UIControlStateNormal];
//        //
//        [titleButton setBackgroundImage:image2 forState:UIControlStateSelected];
        titleButton.titleLabel.layer.cornerRadius = 5;
        titleButton.titleLabel.clipsToBounds = YES;
        [titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        //        titleButton.backgroundColor = RandomColor;
        // 监听按钮点击
        [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
        
        // 把标题按钮保存到对应的数组
        [self.titleButtons addObject:titleButton];
        
        if (i == 0) {
            [self titleClick:titleButton];
            [self.titleScrollView setContentOffset: CGPointMake(0, 0) animated:NO];
        }
        lastW = CGRectGetMaxX(titleButton.frame);
        [self.titleScrollView addSubview:titleButton];
    }
    rightBtn.x = screenW - rightBtn.width;
    rightBtn.y = self.titleScrollView.y;
    rightBtn.height = self.titleScrollView.height;
//    KDLog(@"%@", NSStringFromCGRect(rightBtn.frame));
    [self.view addSubview:rightBtn];
    //如果总btn宽度小于titleScrollView.width，就不启动居中展示效果
    self.needDisplayCenter = (lastW > self.titleScrollView.width);
    // 设置标题的滚动范围
    self.titleScrollView.contentSize = CGSizeMake(lastW +rightBtn.width, 0);
    self.titleScrollView.showsHorizontalScrollIndicator = NO;
    
    // 设置内容的滚动范围
    self.contentScrollView.contentSize = CGSizeMake(count * screenW, 0);
    
    // bug:代码跟我的一模一样,但是标题就是显示不出来
    // 内容往下移动,莫名其妙
}
- (void)setupManageBtn{
    self.btnType = 1;
    // 已经把内容展示上去 -> 展示的效果是否是我们想要的(调整细节)
    if (self.titleButtons.count) {
        [self.titleButtons removeAllObjects];
        self.underLine = nil;
        for (UIButton *btn in self.titleScrollView.subviews) {
            if ([btn isKindOfClass:[UIButton class]]) {
                [btn removeFromSuperview];
            }
        }
    }
    
    // 添加所有标题按钮
    NSInteger count = self.childViewControllers.count;
    CGFloat btnW = screenW /count;
    CGFloat btnH = self.titleScrollView.bounds.size.height;
    CGFloat btnX = 0;
    CGFloat lastW = 0.0;
    //创建底部线
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, btnH - 2, btnW, 2)];
    line.backgroundColor = KDSelectColor;
    [self.titleScrollView addSubview:line];
    self.underLine = line;

    for (NSInteger i = 0; i < count; i++) {
        
        UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
        titleButton.tag = i;
        if (i == 0) {
            btnX = 0;
        }else{
            btnX = lastW;
        }
        UIViewController *vc = self.childViewControllers[i];
        [titleButton setTitle:vc.title forState:UIControlStateNormal];
        titleButton.frame = CGRectMake(btnX, 0, btnW, btnH);
        [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
        [titleButton setTitleColor:KDSelectColor forState:UIControlStateSelected];
        [titleButton setTitleColor:WQColor(0, 0, 0) forState:UIControlStateNormal];
        titleButton.layer.borderWidth = 0.5;
        titleButton.layer.borderColor = WQColor(234, 234, 234).CGColor;
        // 把标题按钮保存到对应的数组
        [self.titleButtons addObject:titleButton];
        if (i == 0) {
            [self titleClick:titleButton];
            [self.titleScrollView setContentOffset: CGPointMake(0, 0) animated:NO];
        }
        lastW = CGRectGetMaxX(titleButton.frame);
        [self.titleScrollView addSubview:titleButton];
    }
    //如果总btn宽度小于titleScrollView.width，就不启动居中展示效果
    self.needDisplayCenter = (lastW > self.titleScrollView.width);
    // 设置标题的滚动范围
    self.titleScrollView.contentSize = CGSizeMake(lastW, 0);
    self.titleScrollView.showsHorizontalScrollIndicator = NO;
    
    // 设置内容的滚动范围
    self.contentScrollView.contentSize = CGSizeMake(count * screenW, 0);
    
}
#pragma mark - 添加标题滚动视图
- (void)setupTitleScrollView
{
    // 创建titleScrollView
    UIScrollView *titleScrollView = [[UIScrollView alloc] init];
//    CGFloat y = self.navigationController.navigationBarHidden? 20 : 64;
    titleScrollView.frame = CGRectMake(0, 0, screenW, 44);
    [self.view addSubview:titleScrollView];
    _titleScrollView = titleScrollView;
}

#pragma mark - 添加内容滚动视图
- (void)setupContentScrollView
{
    // 创建contentScrollView
    UIScrollView *contentScrollView = [[UIScrollView alloc] init];
    CGFloat y = CGRectGetMaxY(self.titleScrollView.frame);
    contentScrollView.frame = CGRectMake(0, y, screenW, self.view.bounds.size.height - y);
    [self.view addSubview:contentScrollView];
    _contentScrollView = contentScrollView;
    
    // 设置contentScrollView的属性
    // 分页
    self.contentScrollView.pagingEnabled = YES;
    // 弹簧
    self.contentScrollView.bounces = NO;
    // 指示器
    self.contentScrollView.showsHorizontalScrollIndicator = NO;
    
    // 设置代理.目的:监听内容滚动视图 什么时候滚动完成
    self.contentScrollView.delegate = self;
    
}

@end
